package com.mxy.myapplication2.java;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.mxy.myapplication2.R;

import java.lang.ref.WeakReference;

/**
 * @author 马晓勇
 */
public class AdapterForCustomizedRefreshExampleList extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    /**
     * headerView的最大高度(单位 px)
     * 设置上限后用户下拉到最大高度后headerView不在拉伸
     */
    private int maxHeight;
    private LayoutInflater lf;
    private MyHeaderViewHolder viewHolder;
    private View flexibleLayout;
    private RecyclerView recyclerView;
    private ObjectAnimator refreshAnim;
    private static MyHandler myHandler;

    private static class MyHandler extends Handler {

        private WeakReference<AdapterForCustomizedRefreshExampleList> weakReference;

        private MyHandler(AdapterForCustomizedRefreshExampleList adapter) {
            this.weakReference = new WeakReference<>(adapter);
        }

        @Override
        public void handleMessage(Message msg) {
            AdapterForCustomizedRefreshExampleList adapter = weakReference.get();
            if (adapter != null) {
                adapter.handlerMessage(msg);
            }
        }
    }

    private void handlerMessage(Message msg) {
        changeFlexibleLayout(flexibleLayout.getLayoutParams().height - 1);
    }

    /**
     * 是否正在执行刷新动画
     */
    private boolean refreshAction = false;

    public AdapterForCustomizedRefreshExampleList(Context context, RecyclerView recyclerView) {
        myHandler = new MyHandler(this);
        this.lf = LayoutInflater.from(context);
        this.recyclerView = recyclerView;
        this.recyclerView.setOnTouchListener(new RvOnTouchListener());
        this.maxHeight = Util.dip2px(context, 120);
    }

    @Override
    public int getItemViewType(int position) {
        return position == 0 ? 0 : 1;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        if (viewType == 0) {
            if (viewHolder == null) {
                if (flexibleLayout == null) {
                    flexibleLayout = lf.inflate(R.layout.item_refreshrv_headerview, viewGroup,
                            false);
                    //注意先初始化footballIv
                    refreshAnim =
                            ObjectAnimator.ofFloat(flexibleLayout.findViewById(R.id.footballIv),
                                    "rotation", 0f, 1440f);
                    refreshAnim.setDuration(2000);
                    refreshAnim.addListener(new RefreshAnimationListener());
                }
                viewHolder = new MyHeaderViewHolder(flexibleLayout);
            }
            return viewHolder;
        } else {
            return new MyViewHolder(lf.inflate(R.layout.item_customizedrefreshexamplelist, null,
                    false));
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {

    }

    @Override
    public int getItemCount() {
        return 1 + 30;
    }

    private class MyHeaderViewHolder extends RecyclerView.ViewHolder {

        private MyHeaderViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }


    /**
     * rv触摸事件
     */
    private class RvOnTouchListener implements View.OnTouchListener {
        /**
         * 用户手指按下位置记录
         */
        private int vertical = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    touchMove(event);
                    break;
                case MotionEvent.ACTION_UP:
                    checkRefreshState();
                    break;
                default:
                    break;
            }
            return false;
        }

        /**
         * 用户手动拖动列表
         */
        private void touchMove(MotionEvent event) {

            // 如果flexibleLayout是隐藏状态,避免用户下拉幅度过大，突然一下flexibleLayout的高度被设置的特别大，这个设置非常重要
            if (flexibleLayout.getLayoutParams().height == 0) {
                // event.getRawY() - 2是因为让接下来计算flexibleLayout初始高度总是从1px开始
                // see ((int) event.getRawY() -vertical)
                vertical = (int) event.getRawY() - 2;
            }

            // 未在刷新状态
            if (!refreshAction) {
                LinearLayoutManager llm = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 完全展示
                int visiableItemCount = llm.findFirstCompletelyVisibleItemPosition();
                // 列表顶部完全展示的item序列
                int firstCompletelyVisibleItem = 2;
                // 列表第1个item完全展示中，可触发headerView的拉伸效果
                if (visiableItemCount < firstCompletelyVisibleItem) {
                    // 当前控件高度
                    int nowHeight = flexibleLayout.getLayoutParams().height;
                    // 改变后高度
                    int newHeight = (int) event.getRawY() - vertical;
                    // 已经最小并且向上拖动或者已经最大并且向下拖动  不做操作
                    if ((nowHeight == 0 && newHeight == 0)
                            || (nowHeight >= maxHeight && newHeight >= maxHeight)) {
                        return;
                    }
                    //除以2是想控制flexibleLayout拉伸的速率，让用户有拽的感觉
                    changeFlexibleLayout(newHeight >> 1);
                } else {
                    if (flexibleLayout.getLayoutParams().height > 0) {
                        changeFlexibleLayout(0);
                    }
                }
            }
        }

        /**
         * 检查是否进入刷新状态
         */
        private void checkRefreshState() {
            if (!refreshAction) {
                if (flexibleLayout.getLayoutParams().height > 0) {
                    //推拽超过一半
                    if (flexibleLayout.getLayoutParams().height >= (maxHeight >> 1)) {
                        //触发刷新
                        collapsFlexibleLayout(false);
                    } else {//拖拽未达到一半
                        //自动折叠起来
                        collapsFlexibleLayout(true);
                    }
                }
            }
        }
    }

    /**
     * 用户手指抬起后  折叠刷新控件
     *
     * @param fullCollaps
     */
    private void collapsFlexibleLayout(boolean fullCollaps) {
        refreshAction = true;
        if (fullCollaps) {
            Util.getExecutorService().execute(new Runnable() {
                @Override
                public void run() {
                    while (flexibleLayout.getLayoutParams().height > 0) {
                        myHandler.sendEmptyMessage(0);
                        try {
                            Thread.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    refreshAction = false;
                }
            });
        } else {
            Util.getExecutorService().execute(new Runnable() {
                @Override
                public void run() {
                    while (flexibleLayout.getLayoutParams().height > (maxHeight >> 1)) {
                        myHandler.sendEmptyMessage(0);
                        try {
                            Thread.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            refreshAnim.start();
        }
    }

    /**
     * 变更FlexibleLayout高度
     *
     * @param newHeight
     */
    private void changeFlexibleLayout(int newHeight) {

        if (newHeight < 0) {
            newHeight = 0;
        }
        flexibleLayout.getLayoutParams().height = newHeight > maxHeight ? maxHeight : newHeight;
        flexibleLayout.requestLayout();
        flexibleLayout.invalidate();
    }


    /**
     * 刷新效果动画监听
     */
    private class RefreshAnimationListener extends AnimatorListenerAdapter {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            //刷新动画完毕 折叠起剩余flexibleLayout
            collapsFlexibleLayout(true);
        }
    }


    private class MyViewHolder extends RecyclerView.ViewHolder {

        private MyViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}